import React, { useEffect, useState } from 'react';
import {
    Card,
    Table,
    Form,
    Input,
    Select,
    Button,
    Space,
    Tag,
    Typography,
    message, Tooltip, Popconfirm
} from 'antd';
import {SearchOutlined, ReloadOutlined, DeleteOutlined, EyeOutlined} from '@ant-design/icons';
import type {ColumnsType, TablePaginationConfig} from 'antd/es/table';
import styles from './index.module.css';
import {textApi, TextDataResponseVO, TextQueryParams} from "../../../services/api/text";
import TextDetailModal from './TextDetailModal';

const { Option } = Select;
const { Text } = Typography;

// 文件类型枚举
const FILE_TYPES = {
    1: '用户直接输入',
    2: 'PDF',
    3: 'DOCX',
    4: 'DOC',
    5: 'TXT'
} as const;

// 语言枚举
const LANGUAGES = {
    zh: '中文',
    en: '英文'
} as const;

const TextListPage: React.FC = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<TextDataResponseVO[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });

    // 获取文件类型对应的标签颜色
    const getFileTypeColor = (fileType: number): string => {
        const colorMap: Record<number, string> = {
            1: 'blue',     // 用户直接输入
            2: 'red',      // PDF
            3: 'green',    // DOCX
            4: 'orange',   // DOC
            5: 'purple'    // TXT
        };
        return colorMap[fileType] || 'default';
    };

    // 处理表格分页、排序、筛选变化
    const handleTableChange = (
        newPagination: TablePaginationConfig,
        filters: any,
        sorter: any
    ) => {
        const values = form.getFieldsValue();
        console.log('表格变化:', {
            pagination: newPagination,
            filters,
            sorter,
            values
        });

        // 获取新的分页参数
        const params = {
            ...values,
            current: newPagination.current || 1,
            pageSize: newPagination.pageSize || 10
        };

        // 更新分页状态
        setPagination({
            current: params.current,
            pageSize: params.pageSize,
            total: pagination.total
        });

        // 重新获取数据
        fetchTexts(params);
    };

    // 查询文本列表
    const fetchTexts = async (params: TextQueryParams) => {
        try {
            setLoading(true);
            console.log('查询参数:', params);

            const response = await textApi.getTextsByPage(params);
            console.log('API响应数据:', response);

            if (response.code === 200) {
                if (response.data && Array.isArray(response.data.records)) {
                    setData(response.data.records);
                    setPagination({
                        current: response.data.current,
                        pageSize: response.data.size,
                        total: response.data.total
                    });
                    console.log('数据更新成功:', {
                        records: response.data.records,
                        pagination: {
                            current: response.data.current,
                            pageSize: response.data.size,
                            total: response.data.total
                        }
                    });
                } else {
                    console.error('返回的数据格式不正确:', response.data);
                    message.error('数据格式错误');
                }
            } else {
                message.error(response.message || '获取数据失败');
            }
        } catch (error) {
            console.error('获取文本列表失败:', error);
            message.error('获取数据失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 处理查询
    const handleSearch = () => {
        const values = form.getFieldsValue();
        setPagination({ ...pagination, current: 1 });
        fetchTexts({ ...values, current: 1, pageSize: pagination.pageSize });
    };

    // 重置查询
    const handleReset = () => {
        form.resetFields();
        setPagination({ ...pagination, current: 1 });
        fetchTexts({ current: 1, pageSize: pagination.pageSize });
    };

    const [detailVisible, setDetailVisible] = useState(false);
    const [currentText, setCurrentText] = useState<TextDataResponseVO | null>(null);

    // 查看详情
    const handleViewDetail = async (textId: number) => {
        try {
            const response = await textApi.getTextById(textId);
            if (response.code === 200 && response.data) {
                setCurrentText(response.data);
                setDetailVisible(true);
            } else {
                message.error(response.message || '获取详情失败');
            }
        } catch (error) {
            console.error('获取详情失败:', error);
            message.error('获取详情失败，请重试');
        }
    };

    // 处理关闭详情
    const handleCloseDetail = () => {
        setDetailVisible(false);
        setCurrentText(null);
    };

    // 删除文本
    const handleDelete = async (textId: number) => {
        try {
            const response = await textApi.deleteText(textId);
            if (response.data.code === 200) {
                message.success('删除成功');
                // 刷新列表
                fetchTexts({
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    ...form.getFieldsValue()
                });
            } else {
                message.error(response.data.message || '删除失败');
            }
        } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败，请重试');
        }
    };
    // 定义表格列
    const columns :ColumnsType<TextDataResponseVO>= [
        {
            title: '文本ID',
            dataIndex: 'textId',
            key: 'textId',
            width: 80,
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            width: 200,
            ellipsis: true,
            render: (title: string) => (
                <Tooltip title={title}>
                    <Text ellipsis style={{ maxWidth: 180 }}>
                        {title || '-'}
                    </Text>
                </Tooltip>
            )
        },
        {
            title: '内容',
            dataIndex: 'content',
            key: 'content',
            width: 300,
            ellipsis: true,
            render: (text: string) => (
                <Text ellipsis={{ tooltip: text }}>
                    {text}
                </Text>
            )
        },
        {
            title: '语言',
            dataIndex: 'language',
            key: 'language',
            width: 100,
            render: (language: string) => (
                <Tag color={language === 'zh' ? 'blue' : 'green'}>
                    {LANGUAGES[language as keyof typeof LANGUAGES] || '未知'}
                </Tag>
            )
        },
        {
            title: '文件类型',
            dataIndex: 'fileType',
            key: 'fileType',
            width: 120,
            render: (fileType: number) => (
                <Tag color={getFileTypeColor(fileType)}>
                    {FILE_TYPES[fileType as keyof typeof FILE_TYPES] || '未知类型'}
                </Tag>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 180,
            render: (time: string) => time ? new Date(time).toLocaleString() : '-'
        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            key: 'updatedAt',
            width: 180,
            render: (time: string) => time ? new Date(time).toLocaleString() : '-'
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            fixed: 'right',
            render: (_: any, record: TextDataResponseVO) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record.textId)}
                    >
                        详情
                    </Button>
                    <Popconfirm
                        title="确定要删除这条文本吗？"
                        onConfirm={() => handleDelete(record.textId)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        }
    ];

    // 首次加载
    useEffect(() => {
        fetchTexts({ current: 1, pageSize: 10 });
    }, []);

    return (
        <div className={styles.container}>
            <Card bordered={false}>
                {/* 查询表单 */}
                <Form
                    form={form}
                    layout="inline"
                    className={styles.queryForm}
                    onFinish={handleSearch}
                >
                    <Form.Item name="content" label="文本内容">
                        <Input
                            placeholder="请输入文本内容"
                            allowClear
                            style={{ width: 200 }}
                        />
                    </Form.Item>

                    <Form.Item name="language" label="语言">
                        <Select
                            placeholder="请选择语言"
                            allowClear
                            style={{ width: 120 }}
                        >
                            <Option value="zh">中文</Option>
                            <Option value="en">英文</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item name="fileType" label="文件类型">
                        <Select
                            placeholder="请选择类型"
                            allowClear
                            style={{ width: 150 }}
                        >
                            {Object.entries(FILE_TYPES).map(([key, value]) => (
                                <Option key={key} value={Number(key)}>{value}</Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item>
                        <Space>
                            <Button
                                type="primary"
                                icon={<SearchOutlined />}
                                onClick={handleSearch}
                            >
                                查询
                            </Button>
                            <Button
                                icon={<ReloadOutlined />}
                                onClick={handleReset}
                            >
                                重置
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>

                {/* 数据调试信息 */}
                {process.env.NODE_ENV === 'development' && (
                    <div style={{ marginBottom: 16 }}>
                        <Text type="secondary">
                            当前数据条数: {data.length},
                            总条数: {pagination.total},
                            当前页: {pagination.current}
                        </Text>
                    </div>
                )}

                {/* 数据表格 */}
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="textId"
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条数据`
                    }}
                    loading={loading}
                    onChange={handleTableChange}
                    scroll={{ x: 1200 }}
                    className={styles.table}
                />
                <TextDetailModal
                    visible={detailVisible}
                    data={currentText}
                    onClose={handleCloseDetail}
                />
            </Card>
        </div>
    );
};

export default TextListPage;
